package com.hxhy.util;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class Tools {

	public static final SimpleDateFormat DATEFORMAT_Y_M_D_HMS = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
	public static final SimpleDateFormat DATEFORMAT_YMDHMS = new SimpleDateFormat("YYYYMMddHHmmss");
	public static final SimpleDateFormat DATEFORMAT_Y_M_D = new SimpleDateFormat("YYYY-MM-dd");
	public static final SimpleDateFormat DATEFORMAT_YMD = new SimpleDateFormat("YYYYMMdd");
	
	private static final Random rd = new Random();

	/**
	 * @取异常信息
	 * @param e
	 * @return
	 */
	public static String getErrorException(Exception e) {
		StackTraceElement[] ste = e.getStackTrace();
		StringBuffer sb = new StringBuffer();
		sb.append(e.getMessage() + "\n");
		for (int i = 0; i < ste.length; i++) {
			sb.append(ste[i].toString() + "\r\n\t");
		}
		return sb.toString();
	}
	
	/**
	 * 获取序列号编号(年月日时分秒+4位随机数字)
	 * 
	 * @return
	 */
	public static String getUUID() {
		
		return DATEFORMAT_YMDHMS.format(new Date()) + left(String.valueOf(rd.nextInt(9999)), 4, "0");
	}

	/**
	 * 非空验证
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean isNullOrEmpty(Object obj) {
		if (obj == null)
			return true;
		if (obj instanceof String && "".equals(obj))
			return true;
		if (obj instanceof String && "NULL".equals(((String) obj).toUpperCase()))
			return true;
		if (obj instanceof Collection && ((Collection<?>) obj).size() == 0)
			return true;
		return false;
	}

	public static String toString(Object obj) {
		if (obj == null)
			return "";
		else if (obj instanceof BigDecimal)
			return ((BigDecimal) obj).toPlainString();
		return obj.toString();
	}
	
	public static String fillNull(Object obj) {
		if (obj == null)
			return "";
		else if (obj instanceof BigDecimal)
			return ((BigDecimal) obj).toPlainString();
		else if(obj instanceof String) {
			String[] ss = ((String) obj).split(",");
			StringBuilder s = new StringBuilder();
			for (String str : ss) {
				if(!isNullOrEmpty(str))
					s.append(",").append(str);
			}
			return s.length() > 0 ? s.substring(1) : "";
		}
		return obj.toString();
	}

	/**
	 * 左补齐
	 * 
	 * @param str源字符串
	 * @param scale位数
	 * @param lpad补充字符
	 * @return
	 */
	public static String left(String str, int scale, String lpad) {
		if (str.length() >= scale)
			return str.substring(0, scale);

		if (isNullOrEmpty(lpad))
			lpad = " ";
		StringBuilder s = new StringBuilder();
		int n = scale - str.length();
		for (int i = 0; i < n; i++) {
			s.append(lpad);
		}
		s.append(str);
		return s.toString();
	}

	/**转化xml字符串为json对象(根节点以下)
	 * @param xmlStr
	 * @return
	 */
	public static JSONObject xmlToJSON(byte[] bytes) {
		JSONObject js = null;
		try {
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document dc = builder.parse(new ByteArrayInputStream(bytes));
			Element ele = dc.getDocumentElement();
			js = new JSONObject();
			parseNode(js, ele);
		} catch (Exception e) {
		}

		return js;
	}
	
	public static JSONObject xmlToJSON(String str) {
		JSONObject js = null;
		XMLSerializer ser = new XMLSerializer();
		js = JSONObject.fromObject(ser.read(str));
		return js;
	}
	
	public static String replaceBlank(String str) {
	    String dest = "";
	    if (str!=null) {
	        Pattern p = Pattern.compile("\\t|\r|\n");
	        Matcher m = p.matcher(str);
	        dest = m.replaceAll("");
	    }
	    return dest;
	}
	
	private static String parseNode(JSONObject js, Node ele) {
		NodeList nodes = ele.getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node.getNodeType() == Node.TEXT_NODE)
				return node.getNodeValue();
			else if (node.getNodeType() == Node.CDATA_SECTION_NODE)
				return node.getNodeValue();
			else if (node.getNodeType() == Node.ELEMENT_NODE) {
				JSONObject jd = new JSONObject();
				String val = parseNode(jd, node);
				if (val != null)
					js.put(node.getNodeName(), val);
				else
					js.put(node.getNodeName(), jd);
			}
		}
		return nodes.getLength() == 0 ? "" : null;
	}
	

}
